import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

// 模拟API请求
const fetchContacts = () => {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve([
                {
                    id: 'g1',
                    name: '前端开发交流群',
                    avatar: '',
                    type: 'group',
                    lastMessage: '张三: 有人解决了那个bug吗?',
                    lastTime: '10:30',
                    unreadCount: 5,
                    announcement: '请大家修改群名片为「姓名-公司」格式',
                    members: ['u1', 'u2', 'u3', 'u4']
                },
                {
                    id: 'u1',
                    name: '张三',
                    avatar: '',
                    type: 'friend',
                    lastMessage: '在吗?有个问题请教',
                    lastTime: '09:15',
                    unreadCount: 3,
                    isOnline: true
                },
                {
                    id: 'u2',
                    name: '李四',
                    avatar: '',
                    type: 'friend',
                    lastMessage: '项目资料已发送',
                    lastTime: '昨天',
                    unreadCount: 0,
                    isOnline: false
                }
            ]);
        }, 500);
    });
};

export const useChatStore = defineStore('chat', () => {
    // 当前登录用户信息
    const currentUser = ref({
        id: 'me',
        name: '我的名字',
        avatar: '',
        status: 'online'
    });

    // 联系人列表
    const contacts = ref([]);

    // 加载状态
    const isLoading = ref(false);

    // 当前选中的聊天
    const currentChat = ref(null);

    // 所有消息（按聊天ID分组）
    const messages = ref({
        /*
        [chatId]: [
          {id, senderId, content, timestamp, type, status}
        ]
        */
    });

    // 群组详情（按群组ID存储）
    const groups = ref({
        /*
        [groupId]: {
          id,
          name,
          avatar,
          announcement,
          ownerId,
          members: [userId],
          createdAt
        }
        */
    });

    // 计算属性：当前聊天消息列表
    const currentMessages = computed(() => {
        if (!currentChat.value) return [];
        return messages.value[currentChat.value.id] || [];
    });

    // 计算属性：当前聊天是否为群聊
    const isGroupChat = computed(() => {
        return currentChat.value?.type === 'group';
    });

    // 计算属性：当前群聊详情
    const currentGroup = computed(() => {
        if (!isGroupChat.value) return null;
        return groups.value[currentChat.value.id] || null;
    });

    // 计算属性：未读消息总数
    const totalUnread = computed(() => {
        return contacts.value.reduce((sum, contact) => sum + (contact.unreadCount || 0), 0);
    });

    // 计算属性：当前聊天成员列表（群聊时使用）
    const chatMembers = computed(() => {
        if (!currentChat.value) return [];

        if (isGroupChat.value && currentGroup.value) {
            return currentGroup.value.members.map(memberId => {
                return contacts.value.find(c => c.id === memberId);
            }).filter(Boolean);
        }

        // 私聊时只显示对方
        return [contacts.value.find(c => c.id === currentChat.value?.id)];
    });

    // 操作：加载联系人
    const loadContacts = async () => {
        isLoading.value = true;
        try {
            const data = await fetchContacts();
            contacts.value = data;

            // 初始化消息存储结构
            data.forEach(contact => {
                if (!messages.value[contact.id]) {
                    messages.value[contact.id] = [];
                }
            });
        } catch (error) {
            console.error('加载联系人失败:', error);
        } finally {
            isLoading.value = false;
        }
    };

    // 操作：选择聊天
    const selectChat = (contact) => {
        currentChat.value = contact;

        // 重置该联系人的未读消息计数
        const contactIndex = contacts.value.findIndex(c => c.id === contact.id);
        if (contactIndex !== -1) {
            contacts.value[contactIndex].unreadCount = 0;
        }

        // 实际项目中这里会加载该聊天的历史消息
        console.log(`已选择聊天: ${contact.name}`);
    };

    // 操作：发送消息
    const sendMessage = (content, type = 'text') => {
        if (!currentChat.value || !content) return;

        const newMessage = {
            id: `msg-${Date.now()}`,
            senderId: currentUser.value.id,
            content,
            type,
            timestamp: new Date().toISOString(),
            status: 'sent'
        };

        // 添加到当前聊天消息列表
        const chatId = currentChat.value.id;
        messages.value[chatId].push(newMessage);

        // 更新联系人的最后消息信息
        const contactIndex = contacts.value.findIndex(c => c.id === chatId);
        if (contactIndex !== -1) {
            contacts.value[contactIndex].lastMessage =
                type === 'text' ? content : `[${type === 'image' ? '图片' : '文件'}]`;
            contacts.value[contactIndex].lastTime = '刚刚';
        }

        return newMessage;
    };

    // 操作：接收消息
    const receiveMessage = (contactId, message) => {
        if (!messages.value[contactId]) {
            messages.value[contactId] = [];
        }

        messages.value[contactId].push(message);

        // 如果消息不是来自当前聊天，增加未读计数
        if (currentChat.value?.id !== contactId) {
            const contactIndex = contacts.value.findIndex(c => c.id === contactId);
            if (contactIndex !== -1) {
                contacts.value[contactIndex].unreadCount =
                    (contacts.value[contactIndex].unreadCount || 0) + 1;
            }
        }

        // 更新最后消息
        const contact = contacts.value.find(c => c.id === contactId);
        if (contact) {
            contact.lastMessage = message.content;
            contact.lastTime = '刚刚';
        }
    };

    // 操作：更新群公告
    const updateGroupAnnouncement = (groupId, announcement) => {
        if (!groups.value[groupId]) return;

        groups.value[groupId].announcement = announcement;

        // 更新联系人中的公告信息
        const contactIndex = contacts.value.findIndex(c => c.id === groupId);
        if (contactIndex !== -1) {
            contacts.value[contactIndex].announcement = announcement;
        }

        // 如果是当前聊天，更新currentChat
        if (currentChat.value?.id === groupId) {
            currentChat.value.announcement = announcement;
        }
    };

    // 操作：添加联系人
    const addContact = (contact) => {
        contacts.value.push(contact);
        messages.value[contact.id] = [];
    };

    // 操作：添加群组成员
    const addGroupMember = (groupId, memberId) => {
        if (!groups.value[groupId]) return;

        if (!groups.value[groupId].members.includes(memberId)) {
            groups.value[groupId].members.push(memberId);
        }
    };

    // 初始化store
    const initStore = async () => {
        await loadContacts();

        // 初始化群组详情
        contacts.value
            .filter(c => c.type === 'group')
            .forEach(group => {
                groups.value[group.id] = {
                    id: group.id,
                    name: group.name,
                    avatar: group.avatar,
                    announcement: group.announcement || '',
                    ownerId: 'u1', // 模拟群主ID
                    members: group.members || [],
                    createdAt: new Date().toISOString()
                };
            });
    };

    return {
        // 状态
        currentUser,
        contacts,
        isLoading,
        currentChat,
        messages,
        groups,

        // 计算属性
        currentMessages,
        isGroupChat,
        currentGroup,
        totalUnread,
        chatMembers,

        // 操作
        loadContacts,
        selectChat,
        sendMessage,
        receiveMessage,
        updateGroupAnnouncement,
        addContact,
        addGroupMember,
        initStore
    };
});